import { container } from "tsyringe";
import { Config } from "../config";
import { Sender } from "../sender";
import { Task } from "../task";
import { httpGet, httpPost } from "../http";
import { parseJson, tryGetSafe, configTokenFactory } from "../../utils/index";
import { CALL_WEB, CONFIG, SENDER, TASK, registerHandler, ACTION_RUN_COMMAND, HTTP_GET, HTTP_POST, ACTION_CONFIG_GET, ACTION_LOG, DEVICE_NAME, DEVICE_UUID, STATUS_BAR_COLOR, TOKEN, CURRENT_ACTIVITY, CURRENT_PACKAGE, SHOW_CONSOLE, PUSH_TOKEN, APP_TITLE, TOOLBAR_BG_COLOR, LISTENERS, CURRENT_TASK, DEVICE_SETTING, LISTENER_ALL, SCRIPT_MANAGER } from "../../tokens/index";
import { execCommand } from "../execCommand";
import { commonRegister } from "./commonRegister";
import { ScriptManager } from "../scriptManager";
export function uiRegister() {
    commonRegister()
    container.registerSingleton(CONFIG, Config);
    container.registerSingleton(SENDER, Sender);
    container.registerSingleton(TASK, Task);
    container.registerSingleton(SCRIPT_MANAGER, ScriptManager);
    container.register(HTTP_GET, {
        useValue: httpGet
    })
    container.register(HTTP_POST, {
        useValue: httpPost
    })
    configTokenFactory(STATUS_BAR_COLOR)
    configTokenFactory(DEVICE_NAME)
    configTokenFactory(TOKEN)
    configTokenFactory(CURRENT_ACTIVITY)
    configTokenFactory(CURRENT_PACKAGE)
    configTokenFactory(SHOW_CONSOLE)
    configTokenFactory(PUSH_TOKEN)
    configTokenFactory(APP_TITLE)
    configTokenFactory(CURRENT_TASK)

    configTokenFactory(DEVICE_SETTING)
    configTokenFactory(DEVICE_UUID)
    configTokenFactory(TOOLBAR_BG_COLOR)
    
    /**
     * 打印日志
     */
    registerHandler({
        type: ACTION_LOG,
        payload: (data) => {
            console.log(data)
        }
    });
    /**
     * 获取配置文件
     */
    registerHandler({
        type: ACTION_CONFIG_GET,
        payload: (data) => {
            const res = tryGetSafe(data, ``)
            if (typeof res === 'object') {
                return JSON.stringify(res)
            } else {
                return res;
            }
        }
    });
    /**
     * 执行命令
     */
    registerHandler({
        type: ACTION_RUN_COMMAND,
        payload: ({ type, payload }) => {
            execCommand(type, ...payload)
        }
    });
    // 注册调用webview函数
    container.register(CALL_WEB, {
        useFactory: () => {
            return (name: string, data: any) => {
                return new Promise((resolve, reject) => {
                    const main: any = ui.findView('main')
                    main.jsBridge.callHandler(name, data, (data: string) => {
                        const val = parseJson(data)
                        resolve(val)
                    })
                })
            }
        }
    })
}